const express = require("express");
const db = require("./../lib/db");

const router = express.Router(); // 使用express路由
router.get("/home", (req, res) => {
    const sql = `
    select * from goods 
    where is_hot = 1
    order by id desc 
    limit 20
    `;
    db.query(sql)
        .then((list) => {
            res.send({ code: 0, data: list });
        })
        .catch((err) => {
            res.send({ code: 1, message: "查询商品失败" });
        });
});
router.get("/info", (req, res) => {
    const id = req.query.id;
    if (!id || id < 1 || isNaN(id)) {
        // 判断是否传入参数 及 参数是否正确
        // 每次请求只能响应一次send
        res.send({
            code: 1,
            message: "参数不正确",
        });
        return;
    }
    db.queryOne("select * from goods where id = ?", id)
        .then((g) => {
            // g.images = [
            //     {
            //         id: 1,
            //         url:
            //             "https://m.360buyimg.com/mobilecms/s750x750_jfs/t1/139934/40/15415/262185/5fb9d8f6E38c3d5f9/331e1cd22c508504.png!q80.dpg.webp",
            //     },
            //     {
            //         id: 2,
            //         url:
            //             "https://m.360buyimg.com/mobilecms/s750x750_jfs/t1/69363/25/15894/252914/5dd73294E09fa4937/05951481a016f7c9.jpg!q80.dpg.webp",
            //     },
            // ]
            g.images = JSON.parse(g.images);
            g.images.unshift(g.picture);
            res.send({ code: 0, data: g });
        })
        .catch((e) => {
            res.send({ code: 2, message: "查询商品信息失败:" + e.message });
        });
});
// 查询多个商品信息
router.get("/list-info", (req, res) => {
    const ids = req.query.ids;
    const sql = `
    select id,title,picture,price from goods 
    where id in (${ids})
    order by id desc 
    `;
    db.query(sql)
        .then((list) => {
            res.send({ code: 0, data: list });
        })
        .catch((err) => {
            res.send({ code: 1, message: "查询商品失败" });
        });
});
// 绑定 /test 路径
router.get("/test", function (req, res) {
    res.send("goods index");
});
router.get("/search", function (req, res) {
    const key = req.query.key;
    const page = req.query.page || 1;
    const size = 12;
    const sql = `select id,title,price,picture,sell_count from goods 
    where title like '%${key}%' limit ?,?`;
    db.query(sql, (page - 1) * size, size)
        .then((list) => {
            res.send({ code: 0, data: list });
        })
        .catch((err) => {
            res.send({ code: 1, message: "查询商品失败" });
        });
});

module.exports = router; // 暴露路由
